package com.longlong.config.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.longlong.config.globalExceptionClass.ErrorHandler;
import com.longlong.vo.ResultBody;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice(basePackages = "com.longlong")
public class ResultResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        System.out.println(converterType);
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 对请求的结果在这里统一返回和处理
        if (body instanceof ErrorHandler) {
            // 1、如果返回的结果是一个异常的结果，就把异常返回的结构数据倒腾到R.fail里面即可
            ErrorHandler errorHandler = (ErrorHandler) body;
            return ResultBody.fail(errorHandler.getStatus(), errorHandler.getMessage());
        } else if (body instanceof String) {
            // 2、因为springmvc数据转换器对String是有特殊处理 StringHttpMessageConverter
            ObjectMapper objectMapper = new ObjectMapper();
            ResultBody r = ResultBody.success(body);
            try {
                return objectMapper.writeValueAsString(r);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return ResultBody.success(body);
    }
}
